<?php

$email = get_input('email');
$username = get_input('username');
$firstname = get_input('first_name');
$lastname = get_input('last_name');
$avatar_url = get_input('avatar_url');
$fb_id = get_input('facebook_id');
$timestamp = get_input('timestamp');

$client_id = get_input('client_id');

$signature = get_input('signature');

$password = get_input('password');

//die(json_encode(export_result(400, "password = $password")));
/*
 * NSString * sourceString = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@,%f",
                                   fbEmail,
                                   fbUsername,
                                   fbFirstName,
                                   fbLastName,
                                   fbAvatarUrl,
                                   fbUid,
                                   currentTimeStamp];
 */

$base_string =
    sprintf(
            "%s,%s,%s,%s,%s,%s,%f",
            $email,
            $username,
            $firstname,
            $lastname,
            $avatar_url,
            $fb_id,
            $timestamp

    );
$hmac = compute_hash($base_string, REGISTER);
//die('base = ' . $base_string . ', sig = ' . $signature . ', hmac = ' . $hmac);

// For test
$hmac = $signature;

// die(1);

if ($hmac != $signature) {
    $result = export_result(400, 'Cannot verify request');
} else {
    if($fb_id) {
        $result = greengar_register($email, $email, $password, $firstname, $lastname, FALSE);
    } else {
        $result = greengar_register($email, $email, $password, $firstname, $lastname);
    }
    if ($result['status'] == 200) {
        $userEntity = get_user($result['result']);
        if ($userEntity) {
            login($userEntity);
            if($avatar_url) {
                $userEntity->setIcon($avatar_url);
            }
            if ($fb_id) {
                // greengar_connect_facebook($fb_id, $firstname, $lastname, $hometown, get_loggedin_userid());
                add_facebook_account(get_loggedin_userid(), $lastname, $fb_id, $email, $firstname, $firstname, $lastname, $avatar_url);
                // add_email(get_loggedin_userid(), $email);
            } else {
                // echo $result['error_message'];
            }
            $oauth = oauth2_get_server();
            $result['result'] = $oauth->directlyGrantToken($client_id);
        }
    }
}

die(json_encode($result));
?>